/* ---<>-----------------------------------
        Includes
---------------------------------------- */



#include <inttypes.h>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include "allocations/daq.h"
#include "util/util.h"

using namespace std;
using namespace DAQ_namespace;

timeval refTime;
timeval time1,time2;

DAQALLOC DAQ;

ringBuffer bufRx;

void init(FT_HANDLE handle);


FT_HANDLE handle;
FT_STATUS status;

EVENT_HANDLE eh;
DWORD eventMsk;
DWORD eventWord;


bool DAQ_initialized = false;

pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;

pthread_cond_t  condition_var   = PTHREAD_COND_INITIALIZER;


int main()
{

    bufRx.bytesInBuffer = 0;

    //initialize the com port
    handle = comPortInit(1000000,5,5);
    //additions to the initialization routine

    eventMsk = FT_EVENT_RXCHAR; //creates an event mask.  The included conditions will be used to block threads with event conditionals

    FTError(FT_SetEventNotification(handle, eventMsk, (PVOID)&eh)); //I believe this call passes the event conditions to the mutex object

    init(handle);

    while(1)
    {
        if(bufRx.bytesInBuffer == 0)receiveFunc();
        else comPortGet();// parse then process any incoming messages

        if(bufRx.dataOverFlow)
        {
            printf("ring buffer over run\r\n");
            break;
        }
    }

    printf("end of program\r\n");

    exit(0);
}

void init(FT_HANDLE handle)
{
//reset of the daq software
DAQ.sendStopProgram(handle);

DAQ.sendAdcInit(handle,(ADC_CH2_bp | ADC_CH0_bp),ADC_CH_GAIN_1X_gc);

DAQ.sendAdcInit(handle,ADC_CH1_bp,ADC_CH_GAIN_1X_gc);

DAQ.sendAdcInit(handle,ADC_CH3_bp,ADC_CH_GAIN_1X_gc);

DAQ.sendDacEnable(handle,DAC_CH0_bp);

DAQ.sendDigitalInEnable(handle);

DAQ.sendEncoderInit(handle,PLOC_D1,1,0,0,DIGFILT_6SAMPLES_gc,1024);

DAQ.sendEncoderInit(handle,PLOC_D4,0,1,1,DIGFILT_6SAMPLES_gc,1024);

DAQ.sendMotorEnable(handle,0x3);

DAQ.sendServoEnable(handle,0xF);

DAQ.sendSetTimerFreq(handle,500);

DAQ.sendStartProgram(handle);

}

